import { Moon, Sun } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useTheme } from '@/components/theme-provider'
import * as React from 'react'

export function ModeToggle() {
    const { theme, setTheme } = useTheme()
    
    // 获取当前实际显示的主题（考虑系统设置）
    const [isDark, setIsDark] = React.useState(false)
    
    React.useEffect(() => {
        const updateIsDark = () => {
            if (theme === 'system') {
                setIsDark(window.matchMedia('(prefers-color-scheme: dark)').matches)
            } else {
                setIsDark(theme === 'dark')
            }
        }
        
        updateIsDark()
        
        // 监听系统主题变化
        const media = window.matchMedia('(prefers-color-scheme: dark)')
        media.addEventListener('change', updateIsDark)
        
        return () => media.removeEventListener('change', updateIsDark)
    }, [theme])
    
    const toggleTheme = () => {
        if (theme === 'system') {
            // 如果当前是跟随系统，切换到相反的固定主题
            setTheme(isDark ? 'light' : 'dark')
        } else {
            // 如果当前是固定主题，切换到相反的固定主题
            setTheme(theme === 'light' ? 'dark' : 'light')
        }
    }
    
    return (
        <Button 
            variant="ghost" 
            size="icon" 
            aria-label="切换主题" 
            onClick={toggleTheme}
        >
            {isDark ? (
                <Sun className="h-5 w-5 transition-all" />
            ) : (
                <Moon className="h-5 w-5 transition-all" />
            )}
        </Button>
    )
}


